<template>
  <div class="app-container">
    <!-- 搜索表单和其他按钮 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="编号" prop="sn">
        <el-input
          v-model="queryParams.sn"
          placeholder="请输入编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:transfer:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:Erpuser:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:transfer:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="transferList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="调拨时间" align="center" prop="transferTime" />
      <el-table-column label="编号" align="center" prop="sn" />
      <el-table-column label="调出部门" align="center" prop="outDeptName" />
      <el-table-column label="调出仓库" align="center" prop="outWarehouseName" />
      <el-table-column label="调入部门" align="center" prop="inDeptName" />
      <el-table-column label="调入仓库" align="center" prop="inWarehouseName" />
      <el-table-column label="调出人" align="center" prop="outHandledByName" />
      <el-table-column label="调入人" align="center" prop="inHandledByName" />
      <el-table-column label="状态" align="center" prop="status" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.status === '未提交'"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:out:edit']"
          >编辑</el-button>
          <el-button
            v-if="scope.row.status === '未提交'"
            size="mini"
            type="text"
            icon="el-icon-upload"
            @click="handleSubmit(scope.row)"
          >提交</el-button>
          <el-button
            v-if="scope.row.status === '已提交'"
            size="mini"
            type="text"
            icon="el-icon-refresh-left"
            @click="handleWithdraw(scope.row)"
          >撤回</el-button>
          <el-button
            v-if="scope.row.status === '已提交'"
            size="mini"
            type="text"
            icon="el-icon-check"
            @click="handleConfirm(scope.row)"
          >确认</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改库存调拨对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <!-- 编号 -->
        <el-form-item label="编号" prop="sn">
          <el-input v-model="form.sn" placeholder="请输入编号" :disabled="form.isAdd" class="form-item-input"/>
        </el-form-item>

        <!-- 调出经手人 -->
        <el-form-item label="调出经手人">
          <el-cascader
            v-model="form.outHandledById"
            :options="personList"
            :props="{ checkStrictly: true, value: 'id', label: 'realName' }"
            placeholder="请选择调出经手人"
            class="form-item-input"
            @change="handleCreatorChange"
          />
        </el-form-item>

        <!-- 调入经手人 -->
        <el-form-item label="调入经手人">
          <el-cascader
            v-model="form.inHandledById"
            :options="personList"
            :props="{ checkStrictly: true, value: 'id', label: 'realName' }"
            placeholder="请选择调入经手人"
            class="form-item-input"
            @change="handleCreatorChange2"
          />
        </el-form-item>

        <!-- 调出部门 -->
        <el-form-item label="调出部门" prop="outDeptId">
          <el-select
            v-model="form.outDeptId"
            placeholder="请选择调出部门"
            clearable
            class="form-item-input"
            @change="handleOutDeptChange"
          >
            <el-option
              v-for="dept in deptOptions"
              :key="dept.id"
              :label="dept.name"
              :value="dept.id"
            />
          </el-select>
        </el-form-item>

        <!-- 调出仓库 -->
        <el-form-item label="调出仓库" prop="outWarehouseId">
          <el-select
            v-model="form.outWarehouseId"
            placeholder="请选择调出仓库"
            clearable
            :disabled="!form.outDeptId"
            class="form-item-input"
            @change="handleOutWarehouseChange"
          >
            <el-option
              v-for="warehouse in warehouseOptions"
              :key="warehouse.id"
              :label="warehouse.name"
              :value="warehouse.id"
            />
          </el-select>
        </el-form-item>

        <!-- 调入部门 -->
        <el-form-item label="调入部门" prop="inDeptId">
          <el-select
            v-model="form.inDeptId"
            placeholder="请选择调入部门"
            clearable
            :disabled="!form.outDeptId || !form.outWarehouseId"
            class="form-item-input"
            @change="handleInDeptChange"
          >
            <el-option
              v-for="dept in deptOptions"
              :key="dept.id"
              :label="dept.name"
              :value="dept.id"
              :disabled="dept.id === form.outDeptId"
            />
          </el-select>
        </el-form-item>

        <!-- 调入仓库 -->
        <el-form-item label="调入仓库" prop="inWarehouseId">
          <el-select
            v-model="form.inWarehouseId"
            placeholder="请选择调入仓库"
            clearable
            :disabled="!form.outDeptId || !form.outWarehouseId || !form.inDeptId"
            class="form-item-input"
            @change="handleInWarehouseChange"
          >
            <el-option
              v-for="warehouse in warehouseOptions"
              :key="warehouse.id"
              :label="warehouse.name"
              :value="warehouse.id"
              :disabled="warehouse.id === form.outWarehouseId"
            />
          </el-select>
        </el-form-item>

        <!-- 调拨时间 -->
        <el-form-item label="调拨时间" prop="transferTime">
          <el-date-picker
            v-model="form.transferTime"
            type="datetime"
            placeholder="选择调拨时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            class="form-item-input"
          />
        </el-form-item>
        <!-- 商品明细 -->
        <el-form-item label="商品明细">
          <el-button
            type="primary"
            size="mini"
            @click="handleSelectProducts"
            :disabled="!form.outWarehouseId || !form.inWarehouseId"
          >
            选择商品
          </el-button>

          <el-dialog
            title="选择商品"
            :visible.sync="productDialogVisible"
            width="80%"
            append-to-body
          >
            <!-- 商品选择表格 -->
            <el-table
              :data="productList"
              border
              @selection-change="handleProductSelectionChange"
            >
              <el-table-column type="selection" width="55"></el-table-column>
              <el-table-column prop="wesn" label="入库单号"></el-table-column>
              <el-table-column prop="sn" label="商品编号"></el-table-column>
              <el-table-column prop="name" label="商品名称"></el-table-column>
              <el-table-column prop="specification" label="规格型号"></el-table-column>
              <el-table-column prop="unit" label="单位"></el-table-column>
              <el-table-column prop="stockNum" label="库存数量"></el-table-column>
            </el-table>

            <div slot="footer" class="dialog-footer">
              <el-button @click="productDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="confirmProductSelection">确定</el-button>
            </div>
          </el-dialog>
          <el-table
            :data="form.productList"
            border
            style="width: 100%; margin-top: 10px"
            v-if="form.productList && form.productList.length > 0"
          >
            <el-table-column
              prop="productName"
              label="商品名称"
              width="180"
              align="center"
            ></el-table-column>

            <el-table-column
              prop="productSn"
              label="商品编号"
              align="center"
            ></el-table-column>

            <el-table-column
              prop="productSpecification"
              label="规格型号"
              align="center"
            ></el-table-column>

            <el-table-column
              prop="productUnit"
              label="单位"
              width="100"
              align="center"
            ></el-table-column>

            <el-table-column
              prop="stockNum"
              label="当前库存"
              width="120"
              align="center"
            ></el-table-column>

            <el-table-column
              prop="num"
              label="调拨数量"
              width="150"
              align="center"
            >
              <template slot-scope="scope">
                <el-input-number
                  v-model="scope.row.num"
                  :min="1"
                  :max="scope.row.stockNum"
                  size="mini"
                  controls-position="right"
                ></el-input-number>
              </template>
            </el-table-column>

            <el-table-column
              label="操作"
              width="100"
              align="center"
            >
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleRemoveProduct(scope.$index)"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listTransfer,
  getTransfer,
  delTransfer,
  addTransfer,
  updateTransfer,
  submitTransfer,
  withdrawTransfer,
  confirmTransfer,
  listGoodsByWarehouse
} from "@/api/system/transfer";
import { listDept } from "@/api/erpsystem/dept";
import { listWarehouse } from "@/api/system/warehouse";
import {
  getCompiler,
} from "@/api/procurementmanagement/plan";

export default {
  name: "Transfer",
  data() {
    return {
      //制表人
      personList:[],
      // 遮罩层
      loading: true,
      // 部门选项
      deptOptions: [],
      // 仓库选项
      warehouseOptions: [],
      // 管理员用户选项
      adminUserOptions: [],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 库存调拨表格数据
      transferList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      productDialogVisible: false,
      productList: [], // 商品列表
      selectedProducts: [], // 临时选中的商品
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sn: null,
        outDeptId: null,
        outWarehouseId: null,
        outHandledById: null,
        outHandledByName: null,
        inDeptId: null,
        inWarehouseId: null,
        inHandledById: null,
        inHandledByName: null,
        outDeptName: null,
        outWarehouseName: null,
        inDeptName: null,
        inWarehouseName: null,
        attachment: null,
        status: null,
        transferTime: null,
        creator: null,
        updater: null
      },
      // 表单参数
      form: {
        outWarehouseId: null,
        inWarehouseId: null,
        productList: [
          {
            productId: 1,
            productSn: 'SP001',
            productName: '商品A',
            productSpecification: '标准版',
            productUnit: '个',
            stockNum: 100,  // 当前库存
            num: 1          // 调拨数量
          },
        ]
      },
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    // 临时测试代码 正式使用时删除
    this.productList = [{
      id: '1',
      sn: 'SP001',
      name: '测试商品',
      specification: '标准',
      unit: '个',
      stockNum: 100
    }];

    // 正式初始化代码
    this.getList();
    this.getDeptOptions();
    this.getWarehouseOptions();
  },
  methods: {
    // 处理选择商品按钮点击
    handleSelectProducts() {
      if (!this.form.outWarehouseId) {
        this.$message.warning('请先选择调出仓库');
        return;
      }

      this.loading = true;
      listGoodsByWarehouse(this.form.outWarehouseId)
        .then(response => {
          console.log('完整响应:', response);

          if (!response || response.code !== 200) {
            throw new Error(response?.msg || '请求失败');
          }

          const goodsList = response.rows || [];

          console.log('API响应:', response);
          console.log('转换后的商品列表:', goodsList);
          if (!Array.isArray(goodsList)) {
            throw new Error('商品数据格式不正确');
          }

          // 转换数据格式以匹配前端预期
          this.productList = goodsList.map(item => ({
            wesn: item.wesn,
            id: item.goodsSn, // 使用商品编号作为唯一标识
            sn: item.goodsSn,
            name: item.goodsName,
            specification: item.specification,
            unit: item.unit || '个', // 默认单位
            stockNum: item.num || 0
          }));

          this.productDialogVisible = true;
        })
        .catch(error => {
          console.error('获取商品列表失败:', error);
          this.$message.error(error.message || '获取商品列表失败');
          this.productList = [];
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 获取商品列表
    getProductList() {
      console.log('获取商品列表，仓库ID:', this.form.outWarehouseId); // 调试
      listGoodsByWarehouse(this.form.outWarehouseId).then(response => {
        console.log('商品列表响应:', response); // 调试
        this.productList = response.data || [];
      }).catch(error => {
        console.error('获取商品列表失败:', error);
        this.$message.error('获取商品列表失败');
        this.productList = [];
      });
    },

    // 处理商品选择变化
    handleProductSelectionChange(selection) {
      this.selectedProducts = selection;
    },

    // 确认商品选择
    confirmProductSelection() {
      if (this.selectedProducts.length === 0) {
        this.$message.warning('请至少选择一个商品');
        return;
      }

      this.selectedProducts.forEach(product => {
        if (!this.form.productList.some(item => item.productSn === product.sn)) {
          this.form.productList.push({
            productId: product.id,
            productSn: product.sn,
            productName: product.name,
            productSpecification: product.specification,
            productUnit: product.unit,
            stockNum: product.stockNum,
            num: 1, // 默认调拨数量
            warehouseEntrySn: product.wesn // 添加入库单号
          });
        }
      });

      this.productDialogVisible = false;
      this.selectedProducts = [];
    },

    // 删除商品
    handleRemoveProduct(index) {
      this.form.productList.splice(index, 1);
    },

    // 在handleUpdate方法中初始化productList
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getTransfer(id).then(response => {
        this.form = response.data;
        // 如果后端返回了productList，直接赋值
        if (response.data.productList) {
          this.form.productList = response.data.productList;
        } else {
          this.form.productList = [];
        }
        this.getCompiler();
        this.form.isAdd = false;
        this.open = true;
        this.title = "修改库存调拨";
      });
    },
    // 处理调出部门选择
    handleOutDeptChange(value) {
      this.form.outDeptId = value;
      this.$forceUpdate();
    },
    // 处理调出仓库选择
    handleOutWarehouseChange(value) {
      this.form.outWarehouseId = value;
      this.$forceUpdate();
    },
    // 处理调入部门选择
    handleInDeptChange(value) {
      this.form.inDeptId = value;
      this.$forceUpdate();
    },
    // 处理调入仓库选择
    handleInWarehouseChange(value) {
      this.form.inWarehouseId = value;
      this.$forceUpdate();
    },
    /** 查询库存调拨列表 */
    getList() {
      this.loading = true;
      listTransfer(this.queryParams).then(response => {
        this.transferList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 获取部门列表 */
    getDeptOptions() {
      listDept().then(response => {
        response.data.forEach(dept => {
          dept.deptName = dept.name;
        });
        this.deptOptions = response.data;
      });
    },
    /** 获取仓库列表 */
    getWarehouseOptions() {
      listWarehouse().then(response => {
        response.rows.forEach(warehouse => {
          warehouse.warehouseName = warehouse.name;
        });
        this.warehouseOptions = response.rows;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        sn: null,
        outDeptId: null,
        outWarehouseId: null,
        outHandledById: null,
        outHandledByName: null,
        inDeptId: null,
        inWarehouseId: null,
        inHandledById: null,
        inHandledByName: null,
        outDeptName: null,
        outWarehouseName: null,
        inDeptName: null,
        inWarehouseName: null,
        attachment: null,
        status: null,
        transferTime: null,
        createTime: null,
        updateTime: null,
        creator: null,
        updater: null,
        productList: [] // 确保包含
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.form.isAdd = true; // 设置新增标识
      this.form.sn = this.generateRandomSn(); // 生成随机编号（包含前缀）
      this.getCompiler(); // 获取编制人
      this.open = true;
      this.title = "添加库存调拨";
    },
    //获取编制人
    getCompiler(){
      getCompiler().then(response => {
        this.personList = response.data;
      })
    },
    handleCreatorChange(value) {
      if (value.length > 0) {
        // 获取选中项的最后一个值作为 id
        const selectedPerson = this.personList.find(person => person.id.toString() === value[value.length - 1].toString());
        if (selectedPerson) {
          this.form.outHandledById = selectedPerson.id; // 保存编制人 ID 到表单
          this.form.outHandledByName = selectedPerson.realName; // 保存编制人名称到表单
        }
      } else {
        this.form.outHandledById = null;
        this.form.outHandledByName = null;
      }
    },
    handleCreatorChange2(value) {
      if (value.length > 0) {
        // 获取选中项的最后一个值作为 id
        const selectedPerson = this.personList.find(person => person.id.toString() === value[value.length - 1].toString());
        if (selectedPerson) {
          this.form.inHandledById = selectedPerson.id; // 保存编制人 ID 到表单
          this.form.inHandledByName = selectedPerson.realName; // 保存编制人名称到表单
        }
      } else {
        this.form.inHandledById = null;
        this.form.inHandledByName = null;
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.planList = this.planList;
          if (this.form.id != null) {
            updateTransfer(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            if (this.form.isAdd) {
              this.form.sn = this.generateRandomSn(); // 提交时重新生成随机编号（包含前缀）
            }
            addTransfer(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除库存调拨编号为"' + ids + '"的数据项？').then(function () {
        return delTransfer(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/transfer/export', {
        ...this.queryParams
      }, `transfer_${new Date().getTime()}.xlsx`)
    },
    /** 提交操作 */
    handleSubmit(row) {
      const id = row.id;
      this.$modal.confirm('是否确认提交库存调拨编号为"' + id + '"的数据项？').then(() => {
        return submitTransfer(id);
      }).then(() => {
        this.$modal.msgSuccess("提交成功");
        this.getList();
      }).catch(() => {
      });
    },
    /** 撤回操作 */
    handleWithdraw(row) {
      const id = row.id;
      this.$modal.confirm('是否确认撤回库存调拨编号为"' + id + '"的数据项？').then(() => {
        return withdrawTransfer(id);
      }).then(() => {
        this.$modal.msgSuccess("撤回成功");
        this.getList();
      }).catch(() => {
      });
    },
    /** 确认操作 */
    handleConfirm(row) {
      const id = row.id;
      this.$modal.confirm('是否确认确认库存调拨编号为"' + id + '"的数据项？').then(() => {
        return confirmTransfer(id);
      }).then(() => {
        this.$modal.msgSuccess("确认成功");
        this.getList();
      }).catch(() => {
      });
    },
    generateRandomSn() {
      const prefix = "TB"; // 随机编号前缀
      const date = new Date();
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const randomNum = Math.floor(Math.random() * 10000).toString().padStart(4, '0');
      return `${prefix}${year}${month}${day}${randomNum}`; // 拼接前缀和随机编号
    },
  }
};
</script>

<style scoped>
/* 统一表单元素样式 */
.form-item-input {
  width: 100% !important;
}

/* 调整表单标签样式 */
.el-form-item__label {
  width: 100px;
  text-align: right;
  padding-right: 12px;
}

/* 调整级联选择器样式 */
.el-cascader {
  width: 100%;
}

/* 调整日期选择器样式 */
.el-date-editor {
  width: 100%;
}

/* 调整选择器下拉菜单宽度 */
.el-select-dropdown {
  min-width: 100% !important;
}

/* 确保表单内容区域宽度一致 */
.el-form-item__content {
  width: calc(100% - 100px);
  margin-left: 100px;
}
</style>
